package com.qianniu.napi.admin.service.akka;

import akka.actor.UntypedActor;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.mapper.CouponTplMapper;
import com.qianniu.napi.admin.mapper.DisplayFenleiMapper;
import com.qianniu.napi.admin.mapper.LeagueMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.SpringUtil;
import com.qianniu.napi.common.util.WeixinUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Created by chenxuebin on 2017/7/30.
 */
public class ResourceActor extends UntypedActor {

    private final static Logger logger = LoggerFactory.getLogger(ResourceActor.class);
    private IResourceService resourceService = (IResourceService) SpringUtil.getBean("resourceServiceImpl");
    private IMerchantAppService merchantAppService = (IMerchantAppService) SpringUtil.getBean("merchantAppServiceImpl");
    private IStoreService storeService = (IStoreService) SpringUtil.getBean("storeServiceImpl");
    private IGoodsService goodsService = (IGoodsService) SpringUtil.getBean("goodsServiceImpl");
    private IBannerService bannerService = (IBannerService) SpringUtil.getBean("bannerServiceImpl");
    private INewsService newsService = (INewsService) SpringUtil.getBean("newsServiceImpl");
    private IGoodsCategoryService goodsCategoryService = (IGoodsCategoryService) SpringUtil.getBean("goodsCategoryServiceImpl");
    private INewsCategoryService newsCategoryService = (INewsCategoryService) SpringUtil.getBean("newsCategoryServiceImpl");
    private INavService navService = (INavService) SpringUtil.getBean("navServiceImpl");
    private LeagueMapper leagueMapper = (LeagueMapper) SpringUtil.getBean("leagueMapper");
    private CouponTplMapper couponTplMapper = (CouponTplMapper) SpringUtil.getBean("couponTplMapper");
    private DisplayFenleiMapper displayFenleiMapper = (DisplayFenleiMapper) SpringUtil.getBean("displayFenleiMapper");

    @Override
    public void onReceive(Object message) {

        if (message instanceof String) {
            String msg = message.toString();
            logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SignActor receive message:" + msg);

            // 格式 type+ywid
            String[] arr = msg.split("@");
            if (arr.length <= 2) return;

            String type = arr[0];
            String ywid = arr[1];//上传时是PIC|acttype

            switch (type) {
                case "MerchantApp":
                    logger.info(">>>>>>switch here[MerchantApp]");
                    //type+ywid+acttype
                    merchantAppRes(ywid, arr[2]);
                    break;
                case "Store":
                    logger.info(">>>>>>switch here[Store]");
                    //type+ywid+acttype
                    storeRes(ywid, arr[2]);
                    break;
                case "Goods":
                    logger.info(">>>>>>switch here[Goods]");
                    //type+ywid+acttype
                    goodsRes(ywid, arr[2]);
                    break;
                case "Banner":
                    logger.info(">>>>>>switch here[Banner]");
                    //type+ywid+acttype
                    bannerRes(ywid, arr[2]);
                    break;
                case "Nav":
                    logger.info(">>>>>>switch here[Nav]");
                    //type+ywid+acttype
                    navRes(ywid, arr[2]);
                    break;
                case "News":
                    logger.info(">>>>>>switch here[News]");
                    //type+ywid+acttype
                    newsRes(ywid, arr[2]);
                    break;
                case "GoodsCategory":
                    logger.info(">>>>>>switch here[GoodsCategory]");
                    //type+ywid+acttype
                    goodsCategoryRes(ywid, arr[2]);
                    break;
                case "NewsCategory":
                    logger.info(">>>>>>switch here[NewsCategory]");
                    //type+ywid+acttype
                    newsCategoryRes(ywid, arr[2]);
                    break;
                case "League":
                    logger.info(">>>>>>switch here[League]");
                    //type+ywid+acttype
                    leagueRes(ywid, arr[2]);
                    break;
                case "CouponTpl":
                    logger.info(">>>>>>switch here[CouponTpl]");
                    //type+ywid+acttype
                    couponTplRes(ywid, arr[2]);
                    break;
                case "DisplayFenlei":
                    logger.info(">>>>>>switch here[DisplayFenlei]");
                    //type+ywid+acttype
                    displayFenleiRes(ywid, arr[2]);
                    break;
                case "uploadfile":
                    logger.info(">>>>>>switch here[uploadfile]");
                    //type+pic+mid+mpid+sid+mediatype+tbtype+fieldname
                    saveUploadRes(arr[1], arr[2], arr[3], arr[4], arr[5], arr[6], arr[7]);
                    break;
                default:
                    break;
            }

            logger.debug(">>>>>> SignActor saveSign success");
        }
    }


    private void merchantAppRes(String ywid, String acttype) {

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> merchantAppRes ");
        MerchantApp bean = merchantAppService.selectById(ywid);
        if (bean == null) {
            return;
        }
        Boolean isupdate = acttype.equals("update");

        savedbRes(ywid, bean.getPic(),"MerchantApp","pic", -1, isupdate);

        savedbRes(ywid, bean.getGzhimg(),"MerchantApp","gzhimg", 1, isupdate);
        savedbRes(ywid, bean.getKefuimg(),"MerchantApp","kefuimg", 1, isupdate);
    }

    private void storeRes(String ywid, String acttype) {

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> storeRes ");
        Store bean = storeService.selectById(ywid);
        if (bean == null) {
            return;
        }
        Boolean isupdate = acttype.equals("update");

        savedbRes(ywid, bean.getPic(),"Store","pic", -1, isupdate);
        savedbRes(ywid, bean.getPhotos(),"Store","photos", -1, isupdate);
        savedbRes(ywid, bean.getXiangqing(),"Store","xiangqing", -1, isupdate);
        savedbRes(ywid, bean.getXukezheng(),"Store","xukezheng", -1, isupdate);
        savedbRes(ywid, bean.getZhizhao(),"Store","zhizhao", -1, isupdate);
        savedbRes(ywid, bean.getZhengshu(),"Store","zhengshu", -1, isupdate);
        savedbRes(ywid, bean.getLogo(),"Store", "logo",-1, isupdate);

        savedbRes(ywid, bean.getGzhimg(),"Store", "gzhimg",1, isupdate);
        savedbRes(ywid, bean.getKefuimg(),"Store","kefuimg", 1, isupdate);
    }

    private void goodsRes(String ywid, String acttype) {

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> goodsRes ");
        Goods bean = goodsService.selectById(ywid);
        if (bean == null) {
            return;
        }
        Boolean isupdate = acttype.equals("update");

        savedbRes(ywid, bean.getPic(), "Goods","pic",-1, isupdate);
        savedbRes(ywid, bean.getPhotos(),"Goods", "photos",-1, isupdate);

        savedbRes(ywid, bean.getInfo(),"Goods", "info",-1, isupdate);
        savedbRes(ywid, bean.getPackinglist(),"Goods","packinglist", -1, isupdate);
        savedbRes(ywid, bean.getAfterservice(),"Goods","afterservice", -1, isupdate);
        savedbRes(ywid, bean.getIntroduction(),"Goods","introduction", -1, isupdate);

        savedbRes(ywid, bean.getShareimg(),"Goods", "shareimg",1, isupdate);
        savedbRes(ywid, bean.getHomeurl(),"Goods", "homeurl",-1, isupdate);

    }

    private void bannerRes(String ywid, String acttype) {

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> bannerRes ");
        Banner bean = bannerService.selectById(ywid);
        if (bean == null) {
            return;
        }
        Boolean isupdate = acttype.equals("update");

        savedbRes(ywid, bean.getPic(),"Banner", "pic",-1, isupdate);
    }

    private void navRes(String ywid, String acttype) {

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> navRes ");
        Nav bean = navService.selectById(ywid);
        if (bean == null) {
            return;
        }
        Boolean isupdate = acttype.equals("update");

        savedbRes(ywid, bean.getPic(), "Nav","pic",-1, isupdate);
    }

    private void newsRes(String ywid, String acttype) {

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> newsRes ");
        News bean = newsService.selectById(ywid);
        if (bean == null) {
            return;
        }
        Boolean isupdate = acttype.equals("update");

        savedbRes(ywid, bean.getPic(), "News","pic",-1, isupdate);
    }

    private void goodsCategoryRes(String ywid, String acttype) {

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> goodsCategoryRes ");
        GoodsCategory bean = goodsCategoryService.selectById(ywid);
        if (bean == null) {
            return;
        }
        Boolean isupdate = acttype.equals("update");

        savedbRes(ywid, bean.getPic(),"GoodsCategory","pic", -1, isupdate);
    }

    private void newsCategoryRes(String ywid, String acttype) {

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> newsCategoryRes ");
        NewsCategory bean = newsCategoryService.selectById(ywid);
        if (bean == null) {
            return;
        }
        Boolean isupdate = acttype.equals("update");

        savedbRes(ywid, bean.getPic(),"NewsCategory","pic", -1, isupdate);
    }

    private void leagueRes(String ywid, String acttype) {

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> newsCategoryRes ");
        League bean = leagueMapper.selectById(ywid);
        if (bean == null) {
            return;
        }
        Boolean isupdate = acttype.equals("update");

        savedbRes(ywid, bean.getPic(),"League","pic", -1, isupdate);
        savedbRes(ywid, bean.getLogo(),"League","logo", -1, isupdate);

        savedbRes(ywid, bean.getWximg(),"League","wximg", 1, isupdate);
    }

    private void couponTplRes(String ywid, String acttype) {

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> couponTplRes ");
        CouponTpl bean = couponTplMapper.selectById(ywid);
        if (bean == null) {
            return;
        }
        Boolean isupdate = acttype.equals("update");

        savedbRes(ywid, bean.getPic(),"CouponTpl","pic", -1, isupdate);
    }

    private void displayFenleiRes(String ywid, String acttype) {

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> displayFenleiRes ");
        DisplayFenlei bean = displayFenleiMapper.selectById(ywid);
        if (bean == null) {
            return;
        }
        Boolean isupdate = acttype.equals("update");

        savedbRes(ywid, bean.getPic(),"DisplayFenlei","pic", -1, isupdate);
    }

    private void savedbRes(String ywid, String pics,String tbtype ,String fieldname, Integer ismedia, Boolean isupdate) {
        logger.debug(String.format(">>>>>>>>>>>>>>>>>>>>>>>> savedbRes ywid=%s pics=%s tbtype=%s fieldname=%s ismedia=%s isupdate=%s",ywid,pics,tbtype,fieldname,ismedia,isupdate));
        if (Strings.isNullOrEmpty(pics)) return;
        String[] picarr = pics.split(";");

        Map<String, Resource> map = new HashMap<String, Resource>();

        if (isupdate) {
            List<Resource> oldlist = resourceService.selectList(new EntityWrapper<Resource>()
                    .eq("ywid", ywid).eq("fieldname", fieldname));
            for (Resource item : oldlist) {
                map.put(item.getPic(), item);
            }
        }

        for (String pic : picarr) {
            Resource resource = resourceService.selectOne(new EntityWrapper<Resource>().eq("pic", pic));
            if (resource == null) {
                logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> savedbRes res is null");
                return;
            }
            if (map.containsKey(pic)) {
                map.remove(pic);
                logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> map.containsKey(pic) and pic=" + pic);
                return;
            }

            Resource nresource = new Resource();
            nresource.setId(resource.getId());

            nresource.setIsuse(1);
            nresource.setYwid(ywid);
            nresource.setIsmedia(-1);
            nresource.setIsuse(1);
            nresource.setModifytime(new Date());

            if (ismedia != null && ismedia == 1) {

                String path = pic.indexOf("//imgcdn.") > 0 ? pic.replace(Constants.IMG_UPLOAD_CDN_HOST, "/fafa/www/images/0cdn/") :
                        pic.replace(Constants.IMG_UPLOAD_HOST, "/fafa/www/images/");

                logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> savedbRes path=" + path);
                JSONObject jo = WeixinUtil.uploadTempMaterial(Constants.WEIXIN_MATERIAL_IMAGE, path, 72,resource.getMpid().toString());

                if (jo != null && jo.containsKey("media_id")) {
                    nresource.setIsmedia(1);
                    nresource.setMediaid(jo.getString("media_id"));
                    nresource.setCreatedat(jo.getLong("created_at"));
                } else {
                    logger.error(">>>>>>>>>>>>>>>>>>>>>>>> savedbRes error for upload media", jo);
                }
            }

            logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> savedbRes nresource=" + JSON.toJSONString(nresource));
            nresource.updateById();

            if (map.containsKey(pic)) map.remove(pic);
        }

        if (map.keySet().size() > 0) {
            Set<String> keys = map.keySet();
            for (String key : keys) {
                Resource res = map.get(key);
                Resource nresource = new Resource();

                nresource.setId(res.getId());
                nresource.setIsuse(-1);
                nresource.setModifytime(new Date());
                nresource.updateById();

            }
        }

    }

    private void saveUploadRes(String pic, String mid, String mpid, String sid,
                               String mediatype, String tbtype, String fieldname) {
        //type+pic+mid+mpid+sid+mediatype+tbtype+fieldname
        Resource res = new Resource();
        res.setPic(pic);
//        res.setName(name);
        res.setName(getResourceName(tbtype+":"+fieldname));

        res.setMid(Long.valueOf(mid));
        res.setMpid(Long.valueOf(mpid));
        sid=sid.replace("null","");
        if(!Strings.isNullOrEmpty(sid))res.setSid(Long.valueOf(sid));
        if(res.getSid()!=null&&res.getSid()==0)res.setSid(null);

        res.setTbtype(tbtype);
        res.setFieldname(fieldname);

        res.setRtype(getRtype(tbtype));
        res.setMediatype(Integer.valueOf(mediatype));

        res.setIsuse(-1);
        res.setIsmedia(-1);
        res.setCreatetime(new Date());
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>> saveUploadRes res=" + JSON.toJSONString(res));

        res.insert();
    }

    private Integer getRtype(String tbtype) {
        if (Strings.isNullOrEmpty(tbtype)) return null;

        switch (tbtype) {
            case "Goods":
                return 1;//商品
            case "GoodsCategory":
                return 2;//商品
            case "Banner":
                return 3;//滚动图
            case "Nav":
                return 4;//分类导航
            case "Store":
                return 5;//商家信息类
            case "MerchantApp":
                return 6;//平台应用类
            case "News":
                return 7;//平台应用类
            case "DisplayFenlei":
                return 8;//平台应用类
            case "CouponTpl":
                return 9;//平台应用类
            case "League":
                return 10;//联盟商圈类
            case "video":
                return 11;//视频
            default:
                break;
        }

        return null;
    }

    private String getRtypeName(String tbtype) {
        if (Strings.isNullOrEmpty(tbtype)) return null;

        switch (tbtype) {
            case "Goods":
                return "商品图";//商品
            case "GoodsCategory":
                return "商品分类图";//商品
            case "Banner":
                return "滚动轮播图";//滚动图
            case "Nav":
                return "分类导航图";//分类导航
            case "Store":
                return "商家信息图";//商家信息类
            case "MerchantApp":
                return "平台应用图";//平台应用类
            case "News":
                return "文章资讯图";//平台应用类
            case "DisplayFenlei":
                return "首页分类图";//平台应用类
            case "CouponTpl":
                return "优惠券图";//平台应用类
            case "League":
                return "联盟商圈图";//平台应用类
            case "video":
                return "视频类";//平台应用类
            default:
                break;
        }

        return null;
    }

    private String getResourceName(String type) {
        if (Strings.isNullOrEmpty(type)) return null;

        switch (type) {
            case "MerchantApp:pic":
                return "平台应用Logo";
            case "MerchantApp:gzhimg":
                return "平台应用公众号二维码";
            case "MerchantApp:kefuimg":
                return "平台应用客服二维码";
            case "Store:pic":
                return "商家门店门店图";
            case "Store:photos":
                return "商家轮播图";
            case "Store:xiangqing":
                return "商家详情图";
            case "Store:xukezheng":
                return "商家许可证";
            case "Store:zhizhao":
                return "商家营业执照";
            case "Store:zhengshu":
                return "商家证书资料";
            case "Store:logo":
                return "商家Logo";
            case "Store:gzhimg":
                return "商家公众号二维码";
            case "Store:kefuimg":
                return "商家客服二维码";
            case "Goods:pic":
                return "商品主图";
            case "Goods:photos":
                return "商品轮播图";
            case "Goods:info":
                return "商品详情图";
            case "Goods:packinglist":
                return "商品包装信息图";
            case "Goods:afterservice":
                return "商品收货服务说明";
            case "Goods:introduction":
                return "商品功能介绍";
            case "Goods:shareimg":
                return "商品转发图";
            case "Goods:homeurl":
                return "商品主页导航图";
            case "Banner:pic":
                return "滚动轮播图";
            case "GoodsCategory:pic":
                return "商品分类图";
            case "Nav:pic":
                return "分类导航图";//分类导航
            case "News:pic":
                return "文章资讯图";//平台应用类
            case "DisplayFenlei:pic":
                return "首页分类图";//平台应用类
            case "CouponTpl:pic":
                return "优惠券图";//平台应用类
            case "League:pic":
                return "联盟商圈主页图";//
            case "League:logo":
                return "联盟商圈Logo";//
            case "League:wximg":
                return "联盟商圈客服二维码";//
            case "video":
                return "视频类";//平台应用类
            default:
                break;
        }

        return null;
    }


}
